package BitCreeekClient; /**
 * @author Ivan Litsvinenka & Emanuele Ricci
 * Classe che gestisce il Thread UDP del Peer adibito a gestire le connessioni con il Tracker inviare messaggi
 * di keep alive
 *
 */

import BitCreekLib.Host;
import BitCreekTracker.KeepAliveUdp;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class PeerUDPThread implements Runnable {

    /**
     * Informazioni sul Peer ( locale )
     */
    private Host localPeer;

    /**
     * Informazioni per connettersi al Tracker
     */
    private Host tracker;

    /**
     * Nome del Torrent
     */
    private String torrentName;

    /**
     * Costruttore di PeerUDPThread
     *
     * @param tracker     Le informazioni relative al Tracker
     * @param localPeer   Informazioni sul peer che si connette al Tracker
     * @param torrentName Il nome del torrent
     */
    public PeerUDPThread ( Host tracker, Host localPeer, String torrentName ) {
        this.tracker = tracker;
        this.localPeer = localPeer;
        this.torrentName = torrentName;
    }

    public void run () {
        try {
            DatagramSocket clientSocket = new DatagramSocket ();
            KeepAliveUdp ka = new KeepAliveUdp ( torrentName, localPeer.getPort () );
            while ( true ) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream ();
                ObjectOutputStream oo = new ObjectOutputStream ( bout );
                oo.writeObject ( ka );
                byte[] data = bout.toByteArray ();
                DatagramPacket dpTorrent = new DatagramPacket ( data, data.length, tracker.getAddress (), tracker.getPort () );
                clientSocket.send ( dpTorrent );
                oo.close ();
                Thread.sleep ( 15000 );
            }


        } catch ( SocketException e ) {
            e.printStackTrace ();
        } catch ( Exception e ) {
            e.printStackTrace ();
        }
    }
}
